package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.mapper.HuanXinUserMapper;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.service.RequestService;
import com.tanhua.dubbo.server.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Date;

@Service(version = "1.0.0")
@Slf4j
public class HuanXinApiImpl implements HuanXinApi {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RequestService requestService;

    @Autowired
    private HuanXinUserMapper huanXinUserMapper;

    /**
     *  获得token
     * @return
     */
    @Override
    public String getToken() {
        return tokenService.getToken();
    }

    /**
     *  注册环信用户
     * @param userId 探花用户id
     * @return
     */
    @Override
    public Boolean register(Long userId) {
        //拼接拼接请求地址
        String targetUrl = this.huanXinConfig.getUrl()
                + this.huanXinConfig.getOrgName() + "/" +
                this.huanXinConfig.getAppName() + "/users";
        //设置用户名和密码
        //构建一个HuanXinUser类
        HuanXinUser huanXinUser = new HuanXinUser();
        huanXinUser.setUsername("HX_"+userId);
        huanXinUser.setUserId(userId);
        huanXinUser.setPassword(IdUtil.simpleUUID());

        //调用通用请求类的方法
        HttpResponse response = requestService.execute(targetUrl, JSONUtil.toJsonStr(Arrays.asList(huanXinUser)), Method.POST);
        //判断是否请求成功
        if (response.isOk()){
            //存储到mysql中
            huanXinUser.setCreated(new Date());
            huanXinUser.setUpdated(huanXinUser.getCreated());

            huanXinUserMapper.insert(huanXinUser);
            return true;
        }
        return false;
    }

    /**
     * 根据用户id查询环信用户
     * @param userId 用户id
     * @return
     */
    @Override
    public HuanXinUser queryHuanXinUser(Long userId) {
        QueryWrapper<HuanXinUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return this.huanXinUserMapper.selectOne(wrapper);
    }

    /**
     * 按照环信的id查询环信的用户信息
     * @param userName 环信id
     * @return 环信对象
     */
    @Override
    public HuanXinUser queryUserByUserName(String userName) {
        QueryWrapper<HuanXinUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userName);
        return this.huanXinUserMapper.selectOne(wrapper);
    }

    /**
     * 添加好友
     * @param userId   自己的id
     * @param friendId 好友的id
     * @return
     */
    @Override
    public Boolean addUserFriend(Long userId, Long friendId) {
        //拼接请求地址
        String targetUrl = huanXinConfig.getUrl()+
                huanXinConfig.getOrgName()+"/"+
                huanXinConfig.getAppName()+"/users/HX_"+
                userId+"/contacts/users/HX_" + friendId;
        try {
            // 404 -> 对方未在环信注册
            return this.requestService.execute(targetUrl, null, Method.POST).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 添加失败
        return false;
    }

    /**
     * 删除好友
     * @param userId   自己的id
     * @param friendId 好友的id
     * @return
     */
    @Override
    public Boolean removeUserFriend(Long userId, Long friendId) {
        //拼接请求地址
        String targetUrl = huanXinConfig.getUrl()+
                huanXinConfig.getOrgName()+"/"+
                huanXinConfig.getAppName()+"/users/HX_"+
                userId+"/contacts/users/HX_" + friendId;

        try {
            // 404 -> 对方未在环信注册
            return this.requestService.execute(targetUrl, null, Method.DELETE).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 删除失败
        return false;
    }

    /**
     * 回复陌生人消息
     * @param targetUserName 发送目标的用户名
     * @param huanXinMessageType 消息类型
     * @param msg
     * @return
     */
    @Override
    public Boolean sendMsgFromAdmin(String targetUserName, HuanXinMessageType huanXinMessageType, String msg) {
        try {
            //构建请求地址
            String targetUrl = this.huanXinConfig.getUrl()
                    + this.huanXinConfig.getOrgName() + "/"
                    + this.huanXinConfig.getAppName() + "/messages";

            //这是请求体中的内容：
            //{"target_type": "users","target": ["user2","user3"],"msg": {"type": "txt","msg": "testmessage"},"from": "user1"}
            String body = JSONUtil.createObj()
                    .set("target_type", "users")
                    .set("target", JSONUtil.createArray().set(targetUserName))
                    .set("msg", JSONUtil.createObj().set("type", huanXinMessageType.getType()).set("msg", msg)).toString();
            //表示消息发送者;无此字段Server会默认设置为“from”:“admin”，有from字段但值为空串(“”)时请求失败
            /*.set("from","")*/
            return requestService.execute(targetUrl,body,Method.POST).isOk();
        } catch (JSONException e) {
            log.error("环信信息发送失败",e);
        }

        return false;
    }
}
